package com.bdqn.t382.controller;

import com.alibaba.fastjson2.JSON;
import com.bdqn.t382.pojo.R;
import com.bdqn.t382.pojo.SysUser;
import com.bdqn.t382.service.SysUserService;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*")
// 该类是一个控制器，处理与用户相关的请求，映射路径为/user
@Controller
@RequestMapping("/user")
public class UserController {
    // 定义日志记录器，用于记录日志信息
    private Logger logger = LoggerFactory.getLogger(UserController.class);
    // 自动注入SysUserService，用于调用用户相关的业务逻辑
    @Autowired
    private SysUserService sysUserService;

    @ResponseBody
    @RequestMapping("/list")
    public Map<String, Object> list(SysUser sysUser, @RequestParam(defaultValue = "1") Integer pageNo) {
        // 每页显示的记录数
        Integer pageSize = 5;
        List<SysUser> list = sysUserService.findList(sysUser, pageNo, pageSize);
        // 调用服务层方法获取总记录数
        Integer totalCount = sysUserService.getSysUserCount(sysUser);
        // 计算总页数，使用(totalCount + pageSize - 1) / pageSize可以确保在总记录数不能被每页记录数整除时，总页数正确加1
        Integer totalPage = (totalCount + pageSize - 1) / pageSize;

        // 处理页码越界问题
        if (pageNo < 1) {
            pageNo = 1;
        } else if (pageNo > totalPage) {
            pageNo = totalPage;
        }

        // 将用户列表、总记录数、总页数、当前页码、每页记录数添加到模型中，以便在视图中使用
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("totalCount", totalCount);
        result.put("totalPage", totalPage);
        result.put("pageNo", pageNo);
        result.put("pageSize", pageSize);
        // 返回用户列表视图
        return result;
    }

    @ResponseBody
    @PostMapping("/add")
    public int add(@RequestBody SysUser sysUser) {
        // 调用服务层方法添加用户，返回受影响的行数
        int saveBatch = sysUserService.saveBatch(sysUser);
        return saveBatch;
        // 如果添加成功，重定向到用户列表页面
    }

    @RequestMapping("/addUser")
    public String addUser() {
        return "addUser";
    }

    @ResponseBody
    @GetMapping("/delete")
    public int delete(@RequestParam Integer id) {
        // 调用服务层方法删除用户，返回受影响的行数
        int count = sysUserService.deleteBatch(id);
        return count;
    }

    @ResponseBody
    @GetMapping("/view")
    public SysUser view(Model model, @RequestParam Integer id) {
        SysUser sysUser = sysUserService.getById(id);
        model.addAttribute("sysUser", sysUser);
        return sysUser;
    }

//    @GetMapping("/toUpdate")
//    public String toUpdate(Model model, @RequestParam Integer id) {
//        // 调用服务层方法根据ID获取用户信息
//        SysUser sysUser = sysUserService.getById(id);
//        // 将用户信息添加到模型中，以便在视图中使用
//        model.addAttribute("sysUser", sysUser);
//        // 返回更新用户页面的视图
//        return "update";
//    }

    @ResponseBody
    @PostMapping("/update")
    public int update(@RequestBody SysUser sysUser) {
        // 调用服务层方法更新用户信息，返回受影响的行数
        int saveBatch = sysUserService.updateBatch(sysUser);
        return saveBatch;
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @ResponseBody
    @RequestMapping("/doLogin")
    public R doLogin(@RequestBody SysUser sysUser, HttpSession session) {
        SysUser user = null;
        if (sysUser.getAccount().length() < 1 || sysUser.getAccount() == null) {
            return R.fail();
        } else {
            user = sysUserService.getSysUserByAccountBiz(sysUser.getAccount());
            if (user == null) {
                logger.info(sysUser.getAccount() + "用户不存在");
                //用户不存在
                //return forward("error.jsp");
                //throw new RuntimeException("用户不存在");
                return R.fail();
            } else if (!user.getPassword().equals(sysUser.getPassword())) {
                //密码不正确
                logger.info(sysUser.getAccount() + "密码错误");
                return R.fail();
            } else {
                logger.info(sysUser.getAccount() + "登录成功");
                //验证成功设置会话
//                setSession(Constants.SESSION_USER, user);
                return R.ok(user);
            }
        }
    }


    @ResponseBody
    @GetMapping("/findByAccount")
    public String findByAccount(@RequestParam String account) throws Exception {
        SysUser sysUser = sysUserService.findByAccount(account);
        Map<String, Object> map = new HashMap<String, Object>();
        if (sysUser != null) {
            map.put("exist", 1);
        } else {
            map.put("exist", 0);
        }
        return JSON.toJSONString(map);
    }
}